package tee;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.util.Optional;

/**
 * @Author: cangyuan
 * @Date: 2023/2/23
 * @Description: 运维侧交互
 */

@Slf4j
@Component
public class HttpRequestUtil {

    public static final String RESULT_OK_CODE = "0";
    // 失败状态码
    public static final String RESULT_FAIL_CODE = "-1";

    /**
     * 调用运维服务 需要返回值的
     *
     * @param url       地址
     * @param obj       body
     * @param beanClass 响应对象
     * @param <T>       范型
     * @return 返回
     */
    public <T> T httpRequest(String url, Object obj, Class<T> beanClass) throws Exception {
        if (ObjectUtil.isNull(obj)) {
            throw new Exception("请求参数不能为空！");
        }
        String data = JSONUtil.toJsonStr(obj);
        log.debug("httpResponseToBean 参数>>>>>>> url:[{}],param:[{}]", url, data);
        try {
            String responseStr = Optional.ofNullable(HttpUtil.post(url, data)).orElse(JSONUtil.toJsonStr(ApiResult.newInstance(false)));
            log.debug("httpResponseToBean 返回>>>>>>> responseStr:[{}]", responseStr);
            String code = String.valueOf(Optional.ofNullable(JSONUtil.parseObj(responseStr).get("code")).orElse(RESULT_FAIL_CODE));
            if (RESULT_OK_CODE.equals(code)) {
                String str = String.valueOf(Optional.ofNullable(JSONUtil.parseObj(responseStr).get("data")).orElse("false"));
                log.debug("httpResponseToBean 返回>>>>>>> str:[{}]", str);
                //请求成功
                return JSONUtil.toBean(JSONUtil.toJsonStr(str), beanClass);
            } else {
                throw new Exception("调用远程接口错误！");
            }
        } catch (Exception e) {
            log.error("verify face httpResponseToBean 调用远程接口错误>>>>>>> url:[{}],data:[{}],beanClass:[{}]", url, data, beanClass.getName(), e);
            throw new Exception("调用远程接口错误！");
        }
    }


    /**
     * 调用console服务 需要返回值的
     *
     * @param url 调用服务地址
     * @param obj 请求数据
     * @return 是否成功
     */
    public boolean httpRequest(String url, Object obj) throws Exception {
        if (ObjectUtil.isNull(obj)) {
            throw new Exception("请求参数不能为空！");
        }
        String data = JSONUtil.toJsonStr(obj);
        log.debug("httpRequest 参数>>>>>>> url:[{}],param:[{}]", url, data);
        try {
            String responseStr = Optional.ofNullable(HttpUtil.post(url, data)).orElse(JSONUtil.toJsonStr(ApiResult.newInstance(false)));
            log.debug("httpRequest 返回>>>>>>> responseStr:[{}]", responseStr);
            String code = String.valueOf(Optional.ofNullable(JSONUtil.parseObj(responseStr).get("code")).orElse(RESULT_FAIL_CODE));
            if (RESULT_OK_CODE.equals(code)) {
                return true;
            } else {
                throw new Exception("调用远程接口错误！");
            }
        } catch (Exception e) {
            log.error("verify face httpRequest 调用远程接口错误>>>>>>> url:[{}],data:[{}]", url, data, e);
            throw new Exception("调用远程接口错误！");
        }
    }

    public <T> T httpRequestGet(String url, Class<T> beanClass) throws Exception {
        log.debug("httpRequestGet 参数>>>>>>> url:[{}],param:[{}]", url);
        try {
            String responseStr = Optional.ofNullable(HttpUtil.get(url)).orElse(JSONUtil.toJsonStr(ApiResult.newInstance(false)));
            log.debug("httpRequestGet 返回>>>>>>> responseStr:[{}]", responseStr);

            String code = String.valueOf(Optional.ofNullable(JSONUtil.parseObj(responseStr).get("code")).orElse(RESULT_FAIL_CODE));
            if (RESULT_OK_CODE.equals(code)) {
                String str = String.valueOf(Optional.ofNullable(JSONUtil.parseObj(responseStr).get("data")).orElse("false"));
                log.debug("httpResponseToBean 返回>>>>>>> str:[{}]", str);
                return JSONUtil.toBean(JSONUtil.toJsonStr(str), beanClass);
            } else {
                throw new Exception("调用远程接口错误！");
            }
        } catch (Exception e) {
            log.error("verify face httpRequestGet 调用远程接口错误>>>>>>> url:[{}],data:[{}],beanClass:[{}]", url, beanClass.getName(), e);
            throw new Exception("调用远程接口错误！");
        }
    }

    public boolean httpGetUrl(String url) throws Exception {
        log.debug("httpGetUrl 参数>>>>>>> url:[{}]", url);
        boolean result = false;
        try {
            int responseStatus = HttpUtil.createGet(url).execute().getStatus();
            log.debug("httpGetUrl 返回>>>>>>> responseStatus:[{}]", responseStatus);
            if (responseStatus == HttpURLConnection.HTTP_OK || responseStatus == HttpURLConnection.HTTP_MOVED_TEMP
                    || responseStatus == HttpURLConnection.HTTP_MOVED_PERM) {
                result = true;
                log.debug("URL can be reached.");
            } else {
                log.debug("URL is not found.");
            }
        } catch (Exception e) {
            throw new Exception("调用远程接口错误！");
        }
        return result;


    }

    private void panduan(int status) {
        if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
            System.out.println("URL is valid and can be reached.");
        } else {
            System.out.println("URL is not valid or cannot be reached.");
        }
    }
}
